package com.easyj.admin.sys.serviceimpl;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.easyj.admin.sys.service.PermissionService;
import com.easyj.admin.db.mapper.PermissionMapper;
import com.easyj.admin.db.mapper.RolePermissionMapper;
import com.easyj.admin.db.mapper.UserRoleMapper;
import com.easyj.base.security.service.SecurityUtil;
import com.easyj.admin.db.model.Permission;
import com.easyj.admin.db.model.Role;
import com.easyj.admin.db.model.RouteMetaVo;
import com.easyj.admin.db.model.RouteVo;



@Service
public class PermissionServiceImpl implements PermissionService{
	
	@Autowired
	private  PermissionMapper permissionMapper;
	
	@Autowired
	private  UserRoleMapper userRoleMapper;
	
	@Autowired
	private  RolePermissionMapper rolePermissionMapper;
	
	
	public List<Permission> getTree(){
		List<Permission> rtn=new ArrayList<Permission>();
		
		Permission filter = new Permission();
		filter.setDeleted(false);
		List<Permission>  list =findList(filter);
		
		if(list!=null) {
			//build tree
	   		for(Permission r:list) {
   				for(Permission parent:list) {
   					if(r!=parent && r.getPid().longValue()==parent.getId().longValue()) {
   						if(parent.getChildren()==null) {
   							parent.setChildren(new ArrayList<Permission>());
   						}	
   						parent.getChildren().add(r);
   						break;
   					}
   				}    
	   			
	   		}
		}
	   		
   		for(Permission m: list) {
   			if(m.getPid()==0l) { //return root...
   				
   				rtn.add(m);
   			}
   		}
   		return rtn;
		
	}
   	public List<Permission> findList(Permission filter){
        return permissionMapper.selectByExample(filter);
    }

	
	public Permission findById(Long id){
		Permission entity= permissionMapper.selectByPrimaryKey(id);
		return entity;
	}
	

	@Transactional
	public int  insertEntity(Permission entity){
	    entity.setCreateTime(new Date());
		entity.setOperatorId(SecurityUtil.getOperatorId());	
		int rtn= permissionMapper.insert(entity);
		return rtn;
	}
	
	@Transactional
	public int  updateEntity(Permission entity){
	    entity.setModifyTime(new Date()); 
		entity.setOperatorId(SecurityUtil.getOperatorId());	
		int rtn= permissionMapper.updateByPrimaryKeySelective(entity);
		return rtn;
	}

	@Transactional
	public int  disableById(Long id){
	    Permission entity= permissionMapper.selectByPrimaryKey(id);
		entity.setDeleted(true);
		entity.setOperatorId(SecurityUtil.getOperatorId());	
		entity.setModifyTime(new Date());
		int rtn= permissionMapper.updateByPrimaryKeySelective(entity);
		return rtn;
	}
	
	@Transactional
	public int  enableById(Long id){
	    Permission entity= permissionMapper.selectByPrimaryKey(id);
	    entity.setDeleted(false);
		entity.setOperatorId(SecurityUtil.getOperatorId());	
		entity.setModifyTime(new Date());
		int rtn= permissionMapper.updateByPrimaryKeySelective(entity);
		return rtn;
	}
	/**
	 * 取得用户路由
	 */
	public  List<RouteVo>  getUserRouteTree(){
		Long  userId=SecurityUtil.getOperatorId();
		
		List<RouteVo> rtn=new ArrayList<RouteVo>() ;
		List<Role> roles=userRoleMapper.selectRolesByUserId(userId);
		if(roles!=null && roles.size()>0) {
			List<Long> ids=new  ArrayList<Long>();
			for(Role role:roles) {
				ids.add(role.getId());
			}
			List<Permission> ps=rolePermissionMapper.selectByRoleIds(ids);
		   
			if(ps!=null) {
				List<RouteVo> Routes=new ArrayList<RouteVo>() ;
				
				for(Permission p:ps) {
					if(p.getType()==1||p.getType()==3) {//路由和分组
						RouteVo vo=new  RouteVo();
						vo.setId(p.getId());
						vo.setPid(p.getPid());
						vo.setType(p.getType());
						if(StringUtils.isBlank(p.getRedirect())) {
						  vo.setRedirect("noredirect");
						}else {
							vo.setRedirect(p.getRedirect());
						}
						vo.setComponent(p.getComponent());
						vo.setHidden(p.getHidden());
						vo.setName(p.getName());
						vo.setPath(p.getPath());
						
						RouteMetaVo meta=new RouteMetaVo();
						meta.setNoCache(!p.getCache());//---
						meta.setTitle(p.getTitle());
						meta.setIcon(p.getIcon());
						vo.setMeta(meta);
						
						Routes.add(vo);
					}	
				}
				//build tree
		   		for(RouteVo r:Routes) {
	   				for(RouteVo parent:Routes) {
	   				   //find parent
	   					if(r!=parent && r.getPid().longValue()==parent.getId().longValue()) {
	   						if(parent.getChildren()==null) {
	   							parent.setChildren(new ArrayList<RouteVo>());
	   						}	
	   						parent.getChildren().add(r);
	   						break;
	   					}
	   				}    
		   			
		   		}
		   		//对分组进行处理,删除分组本身，把其子加入上一级
		   		for(RouteVo r:Routes) {
		   			if(r.getType()==3) {
		   				for(RouteVo parent:Routes) {
		   					//find parent
		   					if(r!=parent && r.getPid().longValue()== parent.getId().longValue()) {
		   						parent.getChildren().remove(r);
		   						if(r.getChildren()!=null && r.getChildren().size()>0) {
		   						   parent.getChildren().addAll(r.getChildren());
		   						}
		   						break;
		   					}
		   				}    
			   			
		   			}
		   		}
		   	    
		   		//return root...
		   		for(RouteVo m: Routes) {
		   			if(m.getPid()==0l) { 
		   				if(!(m.getPath().startsWith("http:")||m.getPath().startsWith("https:"))) {//不是外部链接
			   				if(!m.getPath().startsWith("/")) {
			   					m.setPath("/"+m.getPath());
			   				}
		   				}
		   				rtn.add(m);
		   			}
		   		}	
		   	}
		}
		
		return rtn;
	}


}
